import axios from 'axios'

import { deleteReqMapItem, setReqMapItem } from './cancel'

/**
 * @description axios实例
 */
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 60 * 1000,
  headers: {
    'Content-Type': 'application/json'
  },
  cancelConfig: {
    enable: true
  }
})

/**
 * @description 请求拦截器
 */
request.interceptors.request.use((config) => {
  if (config.cancelConfig.enable) {
    const { signal, requestId } = setReqMapItem(config)
    config.signal = signal
    config.cancelConfig.__requestId = requestId
  }
  return config
})

/**
 * @description 响应拦截器
 */
request.interceptors.response.use(
  (response) => {
    const __requestId = response.config.cancelConfig.__requestId
    __requestId && deleteReqMapItem(__requestId)
    return response.data
  },
  (error) => {
    const __requestId = error.config.cancelConfig.__requestId
    __requestId && deleteReqMapItem(__requestId)
    return error
  }
)

export default request
